const App = getApp()
const util = require('../../utils/util.js')
Page({
  data: {
    orderType: '',
    desc: '',
    date: '',
    time: '',
    checked: false,
    totalAmount: '', // 实际支付
    total: '', // 合计
    intMoney: 0,
    intVal: '',
    userInfo: {
      discount: 0, // 用户优惠金额 
      consignee: '', // 联系人 
      phone: '', // 联系电话 
      appointmentTime: '', // 预约时间 
    },
    status: 0,
    png: false,
    showInvoice: false,
    showIntegral: false
  },
  onLoad(option) {
    let defaultCar = wx.getStorageSync('defaultCar')
    let products = wx.getStorageSync('products')
    let userId = wx.getStorageSync('userId')
    let agent = wx.getStorageSync('agent')
    let goodsInfo = []
    let intMoney = 0
    let nowDate = new Date().getTime()
    products.forEach(item => {
      item.pricetotal = (Number(item.price) * item.num).toFixed(2)
      goodsInfo.push({
        goodsId: item.id,
        num: item.num
      })
    })
    this.setData({
      merchant: option,
      defaultCar,
      products,
      goodsInfo,
      userId,
      agent,
      'userInfo.consignee': defaultCar.linkman,
      'userInfo.phone': defaultCar.phone,
      date: util.formatTime(new Date(nowDate + 24 * 60 * 60 * 1000)).date,//; 时间推后24小时
      time: util.formatTime(new Date()).hhmm,
      intMoney: intMoney.toFixed(2)
    })
    this.discount()
    this.userInfo()
  },
  onShow() {
    // this.discount()
  },
  discount() { // 优惠活动
    let { userId, agent } = this.data
    let params = {
      buyerId: userId,
      sellerId: agent.id
    }
    App.HttpService.discount(params).then(res => {
      let data = res.data.data
      if (res.data.code == 200) {
        if (data.buyerStatus == 1 && data.sellerStatus == 1) {
          this.setData({ 'userInfo.discount': data.sellerValue })
        }
        this.calAmount()
      }
    })
  },
  userInfo() { // 获取积分
    let { userId } = this.data
    App.HttpService.userInfo({ userId: userId }).then(res => {
      let data = res.data
      if (data.code == 200) {
        let integral = data.data.consumeInfo
        integral.score = data.data.userInfo.score
        this.setData({ integral: integral })
      }
    })
  },
  calAmount() { //计算总价格
    let { userInfo, products } = this.data
    let total = 0
    products.forEach(item => {
      total += item.num * item.price
    })
    total = total - userInfo.discount
    total = total.toFixed(2)
    this.setData({ total, totalAmount: total })
  },
  bindDateChange(e) { // 预约日期
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange(e) { // 预约时间
    this.setData({
      time: e.detail.value
    })
  },
  inputBlur(e) { // 失去焦点时间
    let { key } = e.currentTarget.dataset
    let { value } = e.detail
    this.setData({ [key]: value })
  },
  bindTextAreaBlur(e) { // 监听到新输入的值
    this.setData({ desc: e.detail.value })
  },
  integralBlur(e) {
    let { value } = e.detail
    let { total, integral } = this.data // total 订单金额
    let scoreVal = (integral.score * integral.coinValue / integral.countsValue).toFixed(2) // 所有积分兑换金额
    let integralVal = (Number(value) * integral.coinValue / integral.countsValue).toFixed(2) // 输入积分兑换金额
    let amount = total
    if (scoreVal - integralVal > 0) { // 输入积分小于所有积分  输入合法
      if (amount - integralVal > 0) { // 输入积分小于订单金额
        total = amount - integralVal
        this.setData({
          totalAmount: total.toFixed(2),
          intMoney: integralVal,
          intVal: value
        })
      } else { // 输入积分大于订单金额 输入积分==订单金额
        total = amount - amount
        let score = Math.ceil(amount * integral.countsValue / integral.coinValue)
        this.setData({
          totalAmount: total.toFixed(2),
          intMoney: amount,
          intVal: score
        })
      }
    } else { // 输入积分大于所有积分 输入不合法 取所有积分
      if (amount - scoreVal > 0) { // 所有积分小于订单金额
        total = amount - scoreVal
        this.setData({
          totalAmount: total.toFixed(2),
          intMoney: scoreVal,
          intVal: integral.score
        })
      } else { // 所有积分大于订单金额 所有积分==订单金额
        total = amount - amount
        let score = Math.ceil(amount * integral.countsValue / integral.coinValue)
        this.setData({
          totalAmount: total.toFixed(2),
          intMoney: amount,
          intVal: score
        })
      }
    }
  },
  checkBoxChange(e) {
    let { checked } = e.currentTarget.dataset
    let { total } = this.data
    let intMoney = 0
    if (checked) {
      this.setData({
        totalAmount: total,
        intVal: '',
        intMoney: intMoney.toFixed(2)
      })
    }
    this.setData({
      checked: !checked
    })
  },
  redirectTo(e) {
    App.WxService.redirectTo('/pages/address/confirm/index', {
      ret: this.data.address_id
    })
  },
  addOrder() {
    let { userInfo, date, time, totalAmount, desc, goodsInfo, agent, userId, merchant, intVal, intMoney } = this.data
    if (userInfo.consignee == '') {
      this.alert('请输入联系人')
      return false
    }
    if (userInfo.phone == '') {
      this.alert('请输入联系电话')
      return false
    }
    if (intVal == '') {
      intVal = 0
    }
    userInfo.appointmentTime = date + ' ' + time
    let params = {
      buyerId: userId,
      sellerId: agent.id,
      goodsInfo,
      shopId: merchant.merchantId,
      totalAmount,
      desc,
      userInfo,
      countsValue: intVal,
      countsAmount: intMoney
    }
    App.HttpService.proOrderSave(params).then(res => {
      let data = res.data
      if (data.code == 200) {
        let config = data.data
        if (config.active) {
          wx.navigateTo({
            url: '/pages/order/list/index?stauts=ALL&back=1'
          })
          wx.removeStorageSync('products')
        } else {
          let payconfig = {
            timeStamp: config.timeStamp,
            nonceStr: config.nonceStr,
            package: config.package,
            signType: config.signType,
            paySign: config.paySign,
          }
          payconfig.success = () => {
            wx.navigateTo({
              url: '/pages/order/list/index?stauts=ALL&back=1'
            })
            wx.removeStorageSync('products')
          }
          wx.requestPayment(payconfig)
        }


      } else {
        wx.showModal({
          title: '提示',
          content: data.msg,
          showCancel: false
        })
      }
    }, e => {
      wx.showModal({
        title: '提示',
        content: '服务器错误',
        showCancel: false
      })
    })
  },
  alert(msg) {
    wx.showToast({
      title: msg,
      image: '../../assets/images/warning.png',
      duration: 1500
    })
  },
  clear() {
    App.HttpService.clearCartByUser().then(res => {
      const data = res.data
      console.log(data)
    })
  },
  // 跳转到商家
  toMerchant() {
    wx.navigateTo({
      url: '/pages/merchantsList/detail/detail',
    })
  },
  // 购物车详情弹窗
  setModalStatus2(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = !this.data.status;
    this.setData({ png: !this.data.png });
    this.setData({ status });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({ animationData2: animation.export() })
    if (status == 1) {
      this.setData({
        showModalStatus2: true
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({ animationData2: animation })
      if (status == 0) {
        this.setData({ showModalStatus2: false })
      }
    }.bind(this), 100)
  },
  // 隐藏购物车弹窗
  setModalStatus3(e) {
    // let { status, index } = e.currentTarget.dataset
    let status = 0;
    this.setData({ png: !this.data.png });
    this.setData({ status });
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({ animationData2: animation.export() })
    if (status == 0) {
      this.setData({
        showModalStatus2: false
      })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({ animationData2: animation })
      if (status == 0) {
        this.setData({ showModalStatus2: false })
      }
    }.bind(this), 100)
  },
  // 是否需要发票
  chooseInvoice(e) {
    this.setData({ showInvoice: e.detail.value });
  },
  // 是否使用积分
  chooseIntegral(e) {
    this.setData({ showIntegral: e.detail.value });
  }
})